),LT=/^[ -~]{0,255}[!-~]$/,JT=/,|=/;class FT{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){e.length>512||(this._internalState=e.split(",").reverse().reduce((e,t)=>{const n=t.trim(),r=n.indexOf("=");if(-1!==r){const i=n.slice(0,r),o=n.slice(r+1,t.length);(function(e){return MT.test(e)})(i)&&function(e){return LT.test(e)&&!JT.test(e)}(o)&&e.set(i,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new FT;return e._internalState=new Map(this._internalState),e}}const DT="traceparent",qT="tracestate",HT=new RegExp("^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$");class $T{inject(e,t,n){const r=qy.getSpanContext(e);if(!r||Wy(e)||!Cy(r))return;const i=`00-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||py.NONE).toString(16)}`;n.set(t,DT,i),r.traceState&&n.set(t,qT,r.traceState.serialize())}extract(e,t,n){const r=n.get(t,DT);if(!r)return e;const i=Array.isArray(r)?r[0]:r;if("string"!=typeof i)return e;const o=function(e){const t=HT.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}(i);if(!o)return e;o.isRemote=!0;const s=n.get(t,qT);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new FT("string"==typeof e?e:void 0)}return qy.setSpanContext(e,o)}fields(){return[DT,qT]}}const jT="baggage";class VT{inject(e,t,n){const r=KT.getBaggage(e);if(!r||Wy(e))return;const i=function(e){return e.getAllEntries().map(([e,t])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(n+=";"+t.metadata.toString()),n})}(r).filter(e=>e.length<=4096).slice(0,180),o=function(e){return e.reduce((e,t)=>{const n=`${e}${""!==e?",":""}${t}`;return n.length>8192?e:n},"")}(i);o.length>0&&n.set(t,jT,o)}extract(e,t,n){const r=n.get(t,jT),i=Array.isArray(r)?r.join(","):r;if(!i)return e;const o={};return 0===i.length?e:(i.split(",").forEach(e=>{const t=function(e){const t=e.split(";");if(t.length<=0)return;const n=t.shift();if(!n)return;const r=n.indexOf("=");if(r<=0)return;const i=decodeURIComponent(n.substring(0,r).trim()),o=decodeURIComponent(n.substring(r+1).trim());let s;return t.length>0&&("string"!=typeof(a=t.join(";"))&&(NT.error("Cannot create baggage metadata from unknown type: "+typeof a),a=""),s={__TYPE__:PT,toString:function(){return a}}),{key:i,value:o,metadata:s};var a}(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:KT.setBaggage(e,KT.createBaggage(o)))}fields(){return[jT]}}class zT extends bT{constructor(e={}){super(e)}register(e={}){var t;qy.setGlobalTracerProvider(this),null!==(t=e.propagator)&&(void 0!==t?KT.setGlobalPropagator(t):KT.setGlobalPropagator(new UT({propagators:[new $T,new VT]}))),function(e){if(null!==e){if(void 0===e){const e=new wT;return e.enable(),void zy.setGlobalContextManager(e)}e.enable(),zy.setGlobalContextManager(e)}}(e.contextManager)}}var GT,WT=(GT=function(e,t){return GT=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},GT(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}GT(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),ZT=function(){function e(){}return e.prototype.createGauge=function(e,t){return c_},e.prototype.createHistogram=function(e,t){return u_},e.prototype.createCounter=function(e,t){return a_},e.prototype.createUpDownCounter=function(e,t){return d_},e.prototype.createObservableGauge=function(e,t){return l_},e.prototype.createObservableCounter=function(e,t){return f_},e.prototype.createObservableUpDownCounter=function(e,t){return h_},e.prototype.addBatchObservableCallback=function(e,t){},e.prototype.removeBatchObservableCallback=function(e){},e}(),YT=function(){},XT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t.prototype.add=function(e,t){},t}(YT),QT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t.prototype.add=function(e,t){},t}(YT),e_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t.prototype.record=function(e,t){},t}(YT),t_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t.prototype.record=function(e,t){},t}(YT),n_=function(){function e(){}return e.prototype.addCallback=function(e){},e.prototype.removeCallback=function(e){},e}(),r_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t}(n_),i_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t}(n_),o_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return WT(t,e),t}(n_),s_=new ZT,a_=new XT,c_=new e_,u_=new t_,d_=new QT,f_=new r_,l_=new i_,h_=new o_,p_=new(function(){function e(){}return e.prototype.getMeter=function(e,t,n){return s_},e}()),g_="metrics",y_=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(e){return oy(g_,e,gy.instance())},e.prototype.getMeterProvider=function(){return sy(g_)||p_},e.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},e.prototype.disable=function(){ay(g_,gy.instance())},e}().getInstance();const m_="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof s.g?s.g:{},b_=Symbol.for("io.opentelemetry.js.api.logs"),w_=m_;class v_{emit(e){}}const S_=new v_,T_=new class{getLogger(e,t,n){return new v_}};class __{constructor(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):S_}}class k_{getLogger(e,t,n){var r;return null!==(r=this.getDelegateLogger(e,t,n))&&void 0!==r?r:new __(this,e,t,n)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:T_}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,n){var r;return null===(r=this._delegate)||void 0===r?void 0:r.getLogger(e,t,n)}}class x_{constructor(){this._proxyLoggerProvider=new k_}static getInstance(){return this._instance||(this._instance=new x_),this._instance}setGlobalLoggerProvider(e){return w_[b_]?this.getLoggerProvider():(w_[b_]=(t=e,n=T_,e=>1===e?t:n),this._proxyLoggerProvider.setDelegate(e),e);var t,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=w_[b_])||void 0===e?void 0:e.call(w_,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,n){return this.getLoggerProvider().getLogger(e,t,n)}disable(){delete w_[b_],this._proxyLoggerProvider=new k_}}const I_=x_.getInstance();let E_=console.error.bind(console);function A_(e,t,n){const r=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:r,writable:!0,value:n})}const P_=(e,t,n)=>{if(!e||!e[t])return void E_("no original function "+String(t)+" to wrap");if(!n)return E_("no wrapper function"),void E_((new Error).stack);const r=e[t];if("function"!=typeof r||"function"!=typeof n)return void E_("original object and wrapper must be functions");const i=n(r,t);return A_(i,"__original",r),A_(i,"__unwrap",()=>{e[t]===i&&A_(e,t,r)}),A_(i,"__wrapped",!0),A_(e,t,i),i},N_=(e,t,n)=>{if(!e)return E_("must provide one or more modules to patch"),void E_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{P_(e,t,n)})}):E_("must provide one or more functions to wrap on modules")},R_=(e,t)=>{if(!e||!e[t])return E_("no function to unwrap."),void E_((new Error).stack);const n=e[t];n.__unwrap?n.__unwrap():E_("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},O_=(e,t)=>{if(!e)return E_("must provide one or more modules to patch"),void E_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{R_(e,t)})}):E_("must provide one or more functions to unwrap on modules")};function C_(e){e&&e.logger&&("function"!=typeof e.logger?E_("new logger isn't a function, not replacing"):E_=e.logger)}C_.wrap=P_,C_.massWrap=N_,C_.unwrap=R_,C_.massUnwrap=O_;class K_{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,n){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(n),this._diag=jy.createComponentLogger({namespace:e}),this._tracer=qy.getTracer(e,t),this._meter=y_.getMeter(e,t),this._logger=I_.getLogger(e,t),this._updateMetricInstruments()}_wrap=P_;_unwrap=R_;_massWrap=N_;_massUnwrap=O_;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,n,r){if(e)try{e(n,r)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class U_ extends K_{constructor(e,t,n){super(e,t,n),this._config.enabled&&this.enable()}}var B_;function M_(e,t,n){let r,i;try{i=e()}catch(e){r=e}finally{if(t(r,i),r&&!n)throw r;return i}}function L_(e,t){return"string"==typeof t?e===t:!!e.match(t)}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(B_||(B_={}));const J_=performance,F_=Math.pow(10,6),D_=Math.pow(10,9);function q_(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*F_)]}function H_(e){return function(e,t){const n=[e[0]+t[0],e[1]+t[1]];return n[1]>=D_&&(n[1]-=D_,n[0]+=1),n}(q_(function(){let e=J_.timeOrigin;if("number"!=typeof e){const t=J_;e=t.timing&&t.timing.fetchStart}return e}()),q_("number"==typeof e?e:J_.now()))}var $_;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}($_||($_={}));const j_=performance,V_=Math.pow(10,6),z_=Math.pow(10,9);function G_(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*V_)]}function W_(){let e=j_.timeOrigin;if("number"!=typeof e){const t=j_;e=t.timing&&t.timing.fetchStart}return e}function Z_(e){if(t=e,Array.isArray(t)&&2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1])return e;var t,n;if("number"==typeof e)return e=z_&&(n[1]-=z_,n[0]+=1),n}(G_(W_()),G_("number"==typeof n?n:j_.now()))):G_(e);if(e instanceof Date)return G_(e.getTime());throw TypeError("Invalid input type")}function Y_(e){return e[0]*z_+e[1]}let X_;function Q_(e,t,n,r=!0){if(t in n&&"number"==typeof n[t]&&(!r||0!==n[t]))return e.addEvent(t,n[t])}function ek(e,t,n=!1,r,i){if(void 0===r&&(r=0!==t[$_.START_TIME]),n||(Q_(e,$_.FETCH_START,t,r),Q_(e,$_.DOMAIN_LOOKUP_START,t,r),Q_(e,$_.DOMAIN_LOOKUP_END,t,r),Q_(e,$_.CONNECT_START,t,r),Q_(e,$_.SECURE_CONNECTION_START,t,r),Q_(e,$_.CONNECT_END,t,r),Q_(e,$_.REQUEST_START,t,r),Q_(e,$_.RESPONSE_START,t,r),Q_(e,$_.RESPONSE_END,t,r)),!i){const n=t[$_.ENCODED_BODY_SIZE];void 0!==n&&e.setAttribute("http.response_content_length",n);const r=t[$_.DECODED_BODY_SIZE];void 0!==r&&n!==r&&e.setAttribute("http.response_content_length_uncompressed",r)}}function tk(){return"undefined"!=typeof location?location.origin:void 0}function nk(e){if("function"==typeof URL)return new URL(e,"undefined"!=typeof document?document.baseURI:"undefined"!=typeof location?location.href:void 0);const t=(X_||(X_=document.createElement("a")),X_);return t.href=e,t}var rk;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(rk||(rk={}));var ik=s(7805);const ok=jy.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});const sk=new TextEncoder;function ak(e){return sk.encode(e).byteLength}const ck={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let uk;function dk(){if(void 0===uk){const e=void 0;e&&e.length>0?(uk={},e.forEach(e=>{uk[e]=!0})):uk=ck}return uk}const fk={"https:":"443","http:":"80"},lk="0.203.0",hk="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof s.g?s.g:{},pk="object"==typeof process&&"node"===process.release?.name;class gk extends U_{component="fetch";version=lk;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",lk,e),this._semconvStability=function(e,t){let n=B_.OLD;const r=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of r??[]){if(t.toLowerCase()===e+"/dup"){n=B_.DUPLICATE;break}t.toLowerCase()===e&&(n=B_.STABLE)}return n}("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const n=this.tracer.startSpan("CORS Preflight",{startTime:t[$_.FETCH_START]},qy.setSpan(zy.active(),e)),r=!(this._semconvStability&B_.OLD);ek(n,t,this.getConfig().ignoreNetworkEvents,void 0,r),n.end(t[$_.RESPONSE_END])}_addFinalSpanAttributes(e,t){const n=nk(t.url);if(this._semconvStability&B_.OLD&&(e.setAttribute(ik.a3,t.status),null!=t.statusText&&e.setAttribute(rk.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(ik.Mm,n.host),e.setAttribute(ik.v8,n.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(ik.ds,navigator.userAgent)),this._semconvStability&B_.STABLE){e.setAttribute("http.response.status_code",t.status),e.setAttribute("server.address",n.hostname);const r=function(e){const t=Number(e.port||fk[e.protocol]);return t&&!isNaN(t)?t:void 0}(n);r&&e.setAttribute("server.port",r)}}_addHeaders(e,t){if(!function(e,t){let n=t||[];return("string"==typeof n||n instanceof RegExp)&&(n=[n]),nk(e).origin===tk()||n.some(t=>{return n=e,"string"==typeof(r=t)?n===r:!!n.match(r);var n,r})}(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return KT.inject(zy.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)KT.inject(zy.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else if(e.headers instanceof Headers)KT.inject(zy.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else if(e.headers instanceof Map)KT.inject(zy.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else{const t={};KT.inject(zy.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(function(e,t){if(!t)return!1;for(const n of t)if(L_(e,n))return!0;return!1}(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const r={};if(this._semconvStability&B_.OLD){const i=(t.method||"GET").toUpperCase();n=`HTTP ${i}`,r[rk.COMPONENT]=this.moduleName,r[ik.rp]=i,r[ik.XV]=e}if(this._semconvStability&B_.STABLE){const i=t.method,o=function(e){const t=dk(),n=e.toUpperCase();return n in t?n:"_OTHER"}(t.method||"GET");n||(n=o),r["http.request.method"]=o,o!==i&&(r["http.request.method_original"]=i),r["url.full"]=e}return this.tracer.startSpan(n,{kind:GS.CLIENT,attributes:r})}_findResourceAndAddNetworkEvents(e,t,n){let r=t.entries;if(!r.length){if(!performance.getEntriesByType)return;r=performance.getEntriesByType("resource")}const i=function(e,t,n,r,i=new WeakSet,o){const s=nk(e),a=function(e,t,n,r,i,o){const s=Y_(t),a=Y_(n);let c=r.filter(t=>{const n=Y_(Z_(t[$_.FETCH_START])),r=Y_(Z_(t[$_.RESPONSE_END]));return t.initiatorType.toLowerCase()===(o||"xmlhttprequest")&&t.name===e&&n>=s&&r<=a});return c.length>0&&(c=c.filter(e=>!i.has(e))),c}(e=s.toString(),t,n,r,i,o);if(0===a.length)return{mainRequest:void 0};if(1===a.length)return{mainRequest:a[0]};const c=function(e){return e.slice().sort((e,t)=>{const n=e[$_.FETCH_START],r=t[$_.FETCH_START];return n>r?1:n1){let e=c[0],t=function(e,t,n){const r=Y_(n),i=Y_(Z_(t));let o,s=e[1];const a=e.length;for(let t=1;t=i&&(!o||c=400&&(e.setStatus({code:ZS.ERROR}),e.setAttribute("error.type",String(n.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,i),this._tasksCount--,this._clearResources(),e.end(r)},300)}_patchConstructor(){return e=>{const t=this;return function(...n){const r=this,i=nk(n[0]instanceof Request?n[0].url:String(n[0])).href,o=n[0]instanceof Request?n[0]:n[1]||{},s=t._createSpan(i,o);if(!s)return e.apply(this,n);const a=t._prepareSpanData(i);function c(e,n){t._applyAttributesAfterFetch(e,o,n),t._endSpan(e,a,{status:n.status||0,statusText:n.message,url:i})}function u(e,n){t._applyAttributesAfterFetch(e,o,n),n.status>=200&&n.status<400?t._endSpan(e,a,n):t._endSpan(e,a,{status:n.status,statusText:n.statusText,url:i})}function d(e,t,n){try{const t=n.clone().body;if(t){const r=t.getReader(),i=()=>{r.read().then(({done:t})=>{t?u(e,n):i()},t=>{c(e,t)})};i()}else u(e,n)}finally{t(n)}}function f(e,t,n){try{c(e,n)}finally{t(n)}}return t.getConfig().measureRequestSize&&function(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const n=e[1];if(!n?.body)return Promise.resolve();if(n.body instanceof ReadableStream){const{body:e,length:t}=function(e){if(!e.pipeThrough)return ok.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,n=0;const r=new Promise(e=>{t=e}),i=new TransformStream({start(){},async transform(e,t){const r=await e;n+=r.byteLength,t.enqueue(e)},flush(){t(n)}});return{body:e.pipeThrough(i),length:r}}(n.body);return n.body=e,t}return Promise.resolve((t=n.body,"undefined"!=typeof Document&&t instanceof Document?(new XMLSerializer).serializeToString(document).length:"string"==typeof t?ak(t):t instanceof Blob?t.size:t instanceof FormData?function(e){let t=0;for(const[n,r]of e.entries())t+=n.length,r instanceof Blob?t+=r.size:t+=r.length;return t}(t):t instanceof URLSearchParams?ak(t.toString()):void 0!==t.byteLength?t.byteLength:void ok.warn("unknown body type")))}var t;{const t=e[0];return t?.body?t.clone().text().then(e=>ak(e)):Promise.resolve()}}(...n).then(e=>{e&&(t._semconvStability&B_.OLD&&s.setAttribute(ik.z4,e),t._semconvStability&B_.STABLE&&s.setAttribute(ik.Me,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((n,a)=>zy.with(qy.setSpan(zy.active(),s),()=>(t._addHeaders(o,i),t._callRequestHook(s,o),t._tasksCount++,e.apply(r,o instanceof Request?[o]:[i,o]).then(d.bind(r,s,n),f.bind(r,s,a)))))}}}_applyAttributesAfterFetch(e,t,n){const r=this.getConfig().applyCustomAttributesOnSpan;r&&M_(()=>r(e,t,n),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)},!0)}_callRequestHook(e,t){const n=this.getConfig().requestHook;n&&M_(()=>n(e,t),e=>{e&&this._diag.error("requestHook",e)},!0)}_prepareSpanData(e){const t=H_(),n=[];if("function"!=typeof PerformanceObserver)return{entries:n,startTime:t,spanUrl:e};const r=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&n.push(t)})});return r.observe({entryTypes:["resource"]}),{entries:n,observer:r,startTime:t,spanUrl:e}}enable(){var e;pk?this._diag.warn("this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()"):("function"==typeof(e=fetch)&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped&&(this._unwrap(hk,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(hk,"fetch",this._patchConstructor()))}disable(){pk||(this._unwrap(hk,"fetch"),this._usedResources=new WeakSet)}}var yk=class extends _v{transport;constructor(e,t=(0,vS.FetchTransport)()){super(e),this.transport=t}async createChannelWithTLS(e){try{return(0,vS.createChannel)(e,this.transport)}catch(t){throw console.error("Channel creation error:",t),new lm("Failed to create channel",{url:e,operation:"createChannel",errorCount:1,errors:t instanceof Error?t.message:String(t)},t)}}createAuthnMiddleware(){return async function*(e,t){const n=(0,Rg.Metadata)(t.metadata).set("X-Requested-With","XMLHttpRequest").set("X-Grpc-Web","1").set("X-Client-Env",zw).set("Content-Type","application/grpc-web+proto");return yield*e.next(e.request,{...t,metadata:n})}.bind(this)}createMiddleware(e){return async function*(t,n){const r=(0,Rg.Metadata)(n.metadata).set("X-Requested-With","XMLHttpRequest").set("X-Grpc-Web","1").set("X-Client-Env",zw).set("Content-Type","application/grpc-web+proto");try{const i=await this.authenticate(e);return yield*t.next(t.request,{...n,metadata:r.set("Authorization",`Bearer ${i}`)})}catch(i){return yield*this.handleMiddlewareError(i,e,t,r,n)}}.bind(this)}async createGrpcClient(e,t,n,r,i){let o;let s={};return o=(0,vS.createClientFactory)(),n&&(s={retry:!0,retryMaxAttempts:3},o=o.use(SS.D)),r&&(o=o.use(r)),{...o.create(e,t,{"*":s}),close:i?()=>_v.releaseChannel(i):void 0}}},mk=class extends yS{buildConnectionManager(e){return new yk(e)}initializeTracerEnv({spanProcessors:e,traceUrls:t}){!function({spanProcessors:e,traceUrls:t}){new zT({spanProcessors:e}).register(),KT.setGlobalPropagator(new $T),function(e){const t=e.tracerProvider||qy.getTracerProvider(),n=e.meterProvider||y_.getMeterProvider(),r=e.loggerProvider||I_.getLoggerProvider();!function(e,t,n,r){for(let i=0,o=e.length;ie.replace(/[.*+?^${}()|[\]\\]/g,"\\")).join("|")}))`)],propagateTraceHeaderCorsUrls:/.*/})]})}({spanProcessors:e,traceUrls:t})}};function bk(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function wk(e,t,n=""){const r=(i=e)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name;var i;const o=e?.length,s=void 0!==t;if(!r||s&&o!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e));return e}function vk(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");bk(e.outputLen),bk(e.blockLen)}function Sk(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Tk(...e){for(let t=0;t>>t}const xk=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ik=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ek(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const Ak=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Pk(e,t,n){return e&t^~e&n}function Nk(e,t,n){return e&t^e&n^t&n}class Rk{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=_k(this.buffer)}update(e){Sk(this),wk(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;t[o++]=128,Tk(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let e=o;eu.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=kk(n,17)^kk(n,19)^n>>>10;Kk[e]=i+Kk[e-7]+r+Kk[e-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(kk(s,6)^kk(s,11)^kk(s,25))+Pk(s,a,c)+Ck[e]+Kk[e]|0,d=(kk(n,2)^kk(n,13)^kk(n,22))+Nk(n,r,i)|0;u=c,c=a,a=s,s=o+t|0,o=i,i=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,a,c,u)}roundClean(){Tk(Kk)}destroy(){this.set(0,0,0,0,0,0,0,0),Tk(this.buffer)}}class Bk extends Uk{A=0|Ok[0];B=0|Ok[1];C=0|Ok[2];D=0|Ok[3];E=0|Ok[4];F=0|Ok[5];G=0|Ok[6];H=0|Ok[7];constructor(){super(32)}}const Mk=Ek(()=>new Bk,Ak(1));function Lk(e){const t="string"==typeof e?function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e):e,n=function(e){if(wk(e),xk)return e.toHex();let t="";for(let n=0;nn?e.create().update(t).digest():t);for(let e=0;enew Fk(e,t).update(n).digest();Dk.create=(e,t)=>new Fk(e,t);const qk=Uint8Array.of(0),Hk=Uint8Array.of(),$k={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:jk,n:Vk,Gx:zk,Gy:Gk,b:Wk}=$k,Zk={publicKey:33,publicKeyUncompressed:65,signature:64,seed:48},Yk=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,Yk),t},Xk=(e,t,n="")=>{const r=(i=e)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name;var i;const o=e?.length,s=void 0!==t;return(!r||s&&o!==t)&&Yk((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e)),e},Qk=e=>new Uint8Array(e),ex=(e,t)=>e.toString(16).padStart(t,"0"),tx=e=>Array.from(Xk(e)).map(e=>ex(e,2)).join(""),nx=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,rx=e=>{const t="hex invalid";if("string"!=typeof e)return Yk(t);const n=e.length,r=n/2;if(n%2)return Yk(t);const i=Qk(r);for(let n=0,o=0;n{const t=Qk(e.reduce((e,t)=>e+Xk(t).length,0));let n=0;return e.forEach(e=>{t.set(e,n),n+=e.length}),t},ox=(e=32)=>(globalThis?.crypto).getRandomValues(Qk(e)),sx=BigInt,ax=(e,t,n,r="bad number: out of range")=>(e=>"bigint"==typeof e)(e)&&t<=e&&e{const n=e%t;return n>=0n?n:t+n},ux=e=>e instanceof gx?e:Yk("Point expected"),dx=e=>cx(cx(e*e)*e+Wk),fx=e=>ax(e,0n,jk),lx=e=>ax(e,1n,jk),hx=e=>0n==(1n&e),px=e=>Uint8Array.of(e);class gx{static BASE;static ZERO;X;Y;Z;constructor(e,t,n){this.X=fx(e),this.Y=lx(t),this.Z=fx(n),Object.freeze(this)}static CURVE(){return $k}static fromAffine(e){const{x:t,y:n}=e;return 0n===t&&0n===n?mx:new gx(t,n,1n)}static fromBytes(e){Xk(e);const{publicKey:t,publicKeyUncompressed:n}=Zk;let r;const i=e.length,o=e[0],s=e.subarray(1),a=wx(s,0,32);if(i===t&&(2===o||3===o)){let e=(e=>{const t=dx(lx(e));let n=1n;for(let e=t,r=(jk+1n)/4n;r>0n;r>>=1n)1n&r&&(n=n*e%jk),e=e*e%jk;return cx(n*n)===t?n:Yk("sqrt invalid")})(a);const t=hx(e);hx(sx(o))!==t&&(e=cx(-e)),r=new gx(a,e,1n)}return i===n&&4===o&&(r=new gx(a,wx(s,32,64),1n)),r?r.assertValidity():Yk("bad point: not on curve")}static fromHex(e){return gx.fromBytes(rx(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=ux(e),a=cx(t*s),c=cx(i*r),u=cx(n*s),d=cx(o*r);return a===c&&u===d}is0(){return this.equals(mx)}negate(){return new gx(this.X,cx(-this.Y),this.Z)}double(){return this.add(this)}add(e){const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=ux(e);let a=0n,c=0n,u=0n;const d=cx(3n*Wk);let f=cx(t*i),l=cx(n*o),h=cx(r*s),p=cx(t+n),g=cx(i+o);p=cx(p*g),g=cx(f+l),p=cx(p-g),g=cx(t+r);let y=cx(i+s);return g=cx(g*y),y=cx(f+h),g=cx(g-y),y=cx(n+r),a=cx(o+s),y=cx(y*a),a=cx(l+h),y=cx(y-a),u=cx(0n*g),a=cx(d*h),u=cx(a+u),a=cx(l-u),u=cx(l+u),c=cx(a*u),l=cx(f+f),l=cx(l+f),h=cx(0n*h),g=cx(d*g),l=cx(l+h),h=cx(f-h),h=cx(0n*h),g=cx(g+h),f=cx(l*g),c=cx(c+f),f=cx(y*g),a=cx(p*a),a=cx(a-f),f=cx(p*l),u=cx(y*u),u=cx(u+f),new gx(a,c,u)}subtract(e){return this.add(ux(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return mx;if((e=>{ax(e,1n,Vk)})(e),1n===e)return this;if(this.equals(yx))return Px(e).p;let n=mx,r=yx;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?n=n.add(i):t&&(r=r.add(i));return n}multiplyUnsafe(e){return this.multiply(e,!1)}toAffine(){const{X:e,Y:t,Z:n}=this;if(this.equals(mx))return{x:0n,y:0n};if(1n===n)return{x:e,y:t};const r=((e,t)=>{(0n===e||t<=0n)&&Yk("no inverse n="+e+" mod="+t);let n=cx(e,t),r=t,i=0n,o=1n,s=1n,a=0n;for(;0n!==n;){const e=r/n,t=r%n,c=i-s*e,u=o-a*e;r=n,n=t,i=s,o=a,s=c,a=u}return 1n===r?cx(i,t):Yk("no inverse")})(n,jk);return 1n!==cx(n*r)&&Yk("inverse invalid"),{x:cx(e*r),y:cx(t*r)}}assertValidity(){const{x:e,y:t}=this.toAffine();return lx(e),lx(t),cx(t*t)===dx(e)?this:Yk("bad point: not on curve")}toBytes(e=!0){const{x:t,y:n}=this.assertValidity().toAffine(),r=Sx(t);return e?ix((e=>px(hx(e)?2:3))(n),r):ix(px(4),r,Sx(n))}toHex(e){return tx(this.toBytes(e))}}const yx=new gx(zk,Gk,1n),mx=new gx(0n,1n,0n);gx.BASE=yx,gx.ZERO=mx;const bx=e=>sx("0x"+(tx(e)||"0")),wx=(e,t,n)=>bx(e.subarray(t,n)),vx=2n**256n,Sx=e=>rx(ex(ax(e,0n,vx),64)),Tx=e=>{const t=bx(Xk(e,32,"secret key"));return ax(t,1n,Vk,"invalid secret key: outside of range")},_x=(e,t=!0)=>yx.multiply(Tx(e)).toBytes(t);Qk(0),px(0),px(1);const kx=e=>t=>{const n=((e=ox(Zk.seed))=>{Xk(e),(e.length1024)&&Yk("expected 40-1024b");const t=cx(bx(e),Vk-1n);return Sx(t+1n)})(t);return{secretKey:n,publicKey:e(n)}},xx=(kx(_x),e=>{const t=Tx(e),n=yx.multiply(t),{x:r,y:i}=n.assertValidity().toAffine();return{d:hx(i)?t:(o=-t,cx(o,Vk)),px:Sx(r)};var o}),Ix=(kx(e=>xx(e).px),Math.ceil(32)+1);let Ex;const Ax=(e,t)=>{const n=t.negate();return e?n:t},Px=e=>{const t=Ex||(Ex=(()=>{const e=[];let t=yx,n=t;for(let r=0;r>=o,a>128&&(a-=256,e+=1n);const c=128*s,u=c,d=c+Math.abs(a)-1,f=s%2!=0,l=a<0;0===a?r=r.add(Ax(f,t[u])):n=n.add(Ax(l,t[d]))}return 0n!==e&&Yk("invalid wnaf"),{p:n,f:r}};var Nx=s(8287).hp,Rx=s(8287).hp;const Ox=e=>{if(e instanceof Uint8Array)return e;if("string"!=typeof e)throw new Error("Expected hex string or Uint8Array");const t=new Uint8Array(e.length/2);for(let n=0;n{let t="";const n=new Uint8Array(e),r=n.byteLength;for(let e=0;egx.fromBytes(t).multiply(Tx(e)).toBytes(n))(Ox(r),Ox(i),!0).slice(1,33);return s=Mk,a=o,c=new Uint8Array(0),u=(new TextEncoder).encode("ecdh-aes-key:"+n),d=32,function(e,t,n,r=32){vk(e),bk(r,"length");const i=e.outputLen;if(r>255*i)throw new Error("Length must be <= 255*HashLen");const o=Math.ceil(r/i);void 0===n?n=Hk:wk(n,void 0,"info");const s=new Uint8Array(o*i),a=Dk.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let e=0;e{const n={},r=e=>{const t=n[e];if(!t)throw new Error("sparkWallet not initialized");return t},i=async(n,r)=>{const i={incomingPayment:!0,result:JSON.stringify({transferId:n,balance:r.toString()}),isResponse:!0};try{const n=await Ux(e,JSON.stringify(i));t.postMessage(JSON.stringify({encrypted:n}))}catch(e){console.log("Encryption error during handleTransfer:",e)}};return{initializeSparkWallet:async({mnemonic:e})=>{try{const t=(e=>Lk(e))(e);if(n[t])return{isConnected:!0};const{wallet:r}=await mk.initialize({mnemonicOrSeed:e,options:{network:"MAINNET",optimizationOptions:{multiplicity:2,auto:!0}}});return e=null,n[t]=r,{isConnected:!0}}catch(e){return console.log("Initialize spark wallet error function",e),{isConnected:!1,error:e.message}}},removeWalletEventListener:({mnemonic:e})=>{const t=r(e);t?.listenerCount("transfer:claimed")&&t.removeAllListeners("transfer:claimed")},addWalletEventListener:({mnemonic:e})=>{const t=r(e);t?.listenerCount("transfer:claimed")||t.on("transfer:claimed",i)},getSparkIdentityPubKey:async({mnemonic:e})=>{try{return await r(e).getIdentityPublicKey()}catch(e){console.log("Get spark identity public key error",e)}},getSparkBalance:async({mnemonic:e})=>{try{const t=r(e),n=await t.getBalance();let i={};for(const[e,t]of n.tokenBalances)i[e]={...t,tokenMetadata:{...t.tokenMetadata,maxSupply:t.tokenMetadata.maxSupply.toString()},balance:t.balance.toString()};return{tokensObject:i,balance:n.balance.toString(),didWork:!0}}catch(e){return console.log("Get spark balance error",e),{didWork:!1}}},getSparkStaticBitcoinL1Address:async({mnemonic:e})=>{try{return await r(e).getStaticDepositAddress()}catch(e){console.log("Get reusable Bitcoin mainchain address error",e)}},queryAllStaticDepositAddresses:async({mnemonic:e})=>{try{return await r(e).queryStaticDepositAddresses()}catch(e){console.log("Query reusable Bitcoin mainchain addresses error",e)}},getSparkStaticBitcoinL1AddressQuote:async({txid:e,mnemonic:t})=>{try{return{didWork:!0,quote:await r(t).getClaimStaticDepositQuote(e)}}catch(e){return console.log("Get reusable Bitcoin mainchain address quote error",e),{didWork:!1,error:e.message}}},refundSparkStaticBitcoinL1AddressQuote:async({depositTransactionId:e,destinationAddress:t,fee:n,mnemonic:i})=>{try{return await r(i).refundStaticDeposit({depositTransactionId:e,destinationAddress:t,fee:n})}catch(e){console.log("Refund reusable Bitcoin mainchain address error",e)}},claimnSparkStaticDepositAddress:async({creditAmountSats:e,outputIndex:t,sspSignature:n,transactionId:i,mnemonic:o})=>{try{return{didWork:!0,response:await r(o).claimStaticDeposit({creditAmountSats:e,sspSignature:n,transactionId:i})}}catch(e){return console.log("Claim static deposit address error",e),{didWork:!1,error:e.message}}},getSparkAddress:async({mnemonic:e})=>{try{return{didWork:!0,response:await r(e).getSparkAddress()}}catch(e){return console.log("Get spark address error",e),{didWork:!1,error:e.message}}},sendSparkPayment:async({receiverSparkAddress:e,amountSats:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).transfer({receiverSparkAddress:e.toLowerCase(),amountSats:t})}}catch(e){return console.log("Send spark payment error",e),{didWork:!1,error:e.message}}},sendSparkTokens:async({tokenIdentifier:e,tokenAmount:t,receiverSparkAddress:n,mnemonic:i})=>{try{return{didWork:!0,response:await r(i).transferTokens({tokenIdentifier:e,tokenAmount:BigInt(t),receiverSparkAddress:n})}}catch(e){return console.log("Send spark token error",e),{didWork:!1,error:e.message}}},getSparkLightningPaymentFeeEstimate:async({invoice:e,amountSat:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).getLightningSendFeeEstimate({encodedInvoice:e.toLowerCase(),amountSats:t})}}catch(e){return console.log("Get spark lightning payment fee estimate error",e),{didWork:!1,error:e.message}}},sendSparkLightningPayment:async({invoice:e,amountSat:t,mnemonic:n,maxFeeSats:i})=>{try{return{didWork:!0,paymentResponse:await r(n).payLightningInvoice({invoice:e.toLowerCase(),maxFeeSats:i,amountSatsToSend:t})}}catch(e){return console.log("Send spark lightning payment error",e),{didWork:!1,error:e.message}}},sendSparkBitcoinPayment:async({onchainAddress:e,exitSpeed:t,amountSats:n,feeQuote:i,deductFeeFromWithdrawalAmount:o,mnemonic:s})=>{try{return{didWork:!0,response:await r(s).withdraw({onchainAddress:e,exitSpeed:t,amountSats:n,feeQuote:i,deductFeeFromWithdrawalAmount:o})}}catch(e){return console.log("Send spark bitcoin payment error",e),{didWork:!1,error:e.message}}},receiveSparkLightningPayment:async({amountSats:e,memo:t,expirySeconds:n,mnemonic:i})=>{try{return{didWork:!0,response:await r(i).createLightningInvoice({amountSats:e,memo:t,expirySeconds:n})}}catch(e){return console.log("Receive spark lightning payment error",e),{didWork:!1,error:e.message}}},getSparkLightningPaymentStatus:async({lightningInvoiceId:e,mnemonic:t})=>{try{return await r(t).getLightningReceiveRequest(e)}catch(e){console.log("Get spark lightning payment status error",e)}},getSparkBitcoinPaymentRequest:async({paymentId:e,mnemonic:t})=>{try{return await r(t).getCoopExitRequest(e)}catch(e){console.log("Get spark bitcoin payment request error",e)}},getSparkBitcoinPaymentFeeEstimate:async({withdrawalAddress:e,amountSats:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).getWithdrawalFeeQuote({amountSats:t,withdrawalAddress:e})}}catch(e){return console.log("Get spark bitcoin payment fee estimate error",e),{didWork:!1,error:e.message}}},getSparkPaymentFeeEstimate:async({amountSats:e,mnemonic:t})=>{try{return await r(t).getSwapFeeEstimate(e)}catch(e){return console.log("Get spark payment fee estimate error",e),0}},getSparkLightningSendRequest:async({id:e,mnemonic:t})=>{try{return await r(t).getLightningSendRequest(e)}catch(e){console.log("Get spark lightning send request error",e)}},getSparkTransactions:async({transferCount:e,offsetIndex:t,mnemonic:n})=>{try{const i=await r(n).getTransfers(e,t);return{transfers:i.transfers.map(e=>(delete e.leaves,e)),offset:i.offset}}catch(e){return console.log("Get spark transactions error",e),{transfers:[]}}},getSparkTokenTransactions:async({ownerPublicKeys:e,issuerPublicKeys:t,tokenTransactionHashes:n,tokenIdentifiers:i,outputIds:o,mnemonic:s,lastSavedTransactionId:a})=>{try{const c=await r(s).queryTokenTransactions({ownerPublicKeys:e,issuerPublicKeys:t,tokenTransactionHashes:n,tokenIdentifiers:i,outputIds:o}),u=c.tokenTransactionsWithStatus.map(e=>{const t=e.tokenTransaction,n=t.tokenOutputs?.[0];return{tokenTransactionHash:e.tokenTransactionHash,tokenTransaction:{clientCreatedTimestamp:t.clientCreatedTimestamp,tokenOutputs:n?[{ownerPublicKey:n.ownerPublicKey,tokenIdentifier:n.tokenIdentifier,tokenAmount:n.tokenAmount}]:[]}}});let d=u;if(a){const e=u.findIndex(e=>Bx.from(Object.values(e.tokenTransactionHash)).toString("hex")===a);-1!==e&&(d=u.slice(0,e))}return{tokenTransactionsWithStatus:d,offset:c.offset}}catch(e){return console.log("Get spark transactions error",e),[]}},findTransactionTxFromTxHistory:async({sparkTxId:e,previousOffset:t=0,previousTxs:n=[],mnemonic:i})=>{try{const o=n.find(t=>t.id===e);if(o)return console.log("Using cache tx history"),{didWork:!0,offset:t,foundTransfers:n,bitcoinTransfer:o};const s=r(i);let a,c=t,u=[];const d=20;for(;ct.id===e);if(n){a=n;break}if(-1===t.offset){console.log("Reached end of transactions (offset: -1)");break}c+=1}return{didWork:!0,offset:c,foundTransfers:u,bitcoinTransfer:a}}catch(e){return console.log("Error finding bitcoin tx from history",e),{didWork:!1,error:e.message}}}}};var Lx=s(8287).hp;!function(e){let t=Mx({sharedKey:null,ReactNativeWebView:window.ReactNativeWebView}),n=null;const r=new Set;let i=0,o=!1,s=!1;async function a(a){try{if("string"!=typeof a.data)return;let c=JSON.parse(a.data);if(c.isResponse)return;if(c.id&&r.has(c.id))return void console.log(`Duplicate message ID ${c.id} ignored`);if(!window.__STARTUP_NONCE__||"__INJECT_NONCE__"===window.__STARTUP_NONCE__)throw new Error("Security error: Startup nonce not properly injected");if("handshake:init"===c?.action&&c?.args?.pubN){if(o)throw new Error("Handshake already complete, ignoring subsequent attempt");if(s)throw new Error("Handshake already in progress, ignoring subsequent attempt");s=!0;const a=await async function(){const e=function(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}(32);return{privateKey:e,publicKey:_x(e,!0)}}();n=Kx(a.privateKey,c.args.pubN,window.__STARTUP_NONCE__),t=Mx({sharedKey:n,ReactNativeWebView:window.ReactNativeWebView});const u={id:c.id,success:!0,type:"handshake:reply",pubW:Lx.from(a.publicKey).toString("hex"),runtimeNonce:await Ux(n,window.__STARTUP_NONCE__),isResponse:!0};return console.log("Session key established with native"),r.add(c.id),o=!0,i=1,void e.postMessage(JSON.stringify(u))}if(!o)throw new Error("Received message before handshake complete");if(c.encrypted){const e=await async function(e,t){try{if(!t.includes("?iv=")||!t.includes("&tag="))throw new Error("Missing IV or auth tag");const[n,r]=t.split("?iv="),[i,o]=r.split("&tag="),s=Rx.from(i,"base64"),a=Rx.from(n,"base64"),c=Rx.from(o,"base64"),u=(0,Jk.aes256gcm)(e,s),d=new Uint8Array([...a,...c]),f=u.decrypt(d);return(new TextDecoder).decode(f)}catch(e){throw console.log("Web decryptMessage err",e),e}}(n,c.encrypted);c=JSON.parse(e)}if(c.id&&r.has(c.id))return void console.log(`Duplicate message ID ${c.id} ignored`);if("number"==typeof c.sequence){if(c.sequence3e4)throw new Error(`SECURITY: Rejected stale message: ${e}ms old`);if(e<-5e3)throw new Error(`SECURITY: Rejected future message: ${e}ms in future`)}if(r.add(c.id),"simulate_crash"===c.action)throw new Error("Crash simulation not allowed in production");if(!t[c.action])throw new Error(`Unknown Spark action: ${c.action}`);const u=await t[c.action](c.args),d={id:c.id,success:!0,result:JSON.stringify(u),isResponse:!0};c=null;const f=await Ux(n,JSON.stringify(d));e.postMessage(JSON.stringify({encrypted:f,isResponse:!0}))}catch(t){if(console.log("Spark WebContext error:",t),n){const r=await Ux(n,JSON.stringify({error:t.message}));e.postMessage(JSON.stringify({encrypted:r,isResponse:!0}))}}}window.addEventListener("message",a),document.addEventListener("message",a),document.addEventListener("securitypolicyviolation",async function(e){const t={type:"security:csp-violation",blocked:e.blockedURI,directive:e.violatedDirective,sourceFile:e.sourceFile,lineNumber:e.lineNumber};if(console.error("CSP VIOLATION:",t),n){const e=await Ux(n,JSON.stringify(t));window.ReactNativeWebView?.postMessage(JSON.stringify({encrypted:e,isResponse:!0}))}else window.ReactNativeWebView?.postMessage(JSON.stringify({...t,isResponse:!0,unencrypted:!0}))})}(window.ReactNativeWebView)})()})();